/**
 * Copyright (C), 2017-2018, XXX有限公司
 * FileName: NioBlockServer
 * Author:   zengjian
 * Date:     2018/9/17 17:58
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package fun.codedesign.jdk.socket.nio.block;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 〈〉<br>
 * 〈一句话描述〉
 *
 * @author zengjian
 * @create 2018/9/17 17:58
 */
public class NioBlockServer {

    private ServerSocketChannel serverSocketChannel;
    private AtomicBoolean started = new AtomicBoolean(false);

    public NioBlockServer() {
        try {
            serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.bind(new InetSocketAddress("localhost", 8080), 1024);
            serverSocketChannel.configureBlocking(false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void start() throws IOException {
        while (true) {
            if (started.compareAndSet(false, true)) {
                System.out.format("服务器启动，监听host:%s,port:%s\n", "localhost", 8080);
            }
            SocketChannel socketChannel = serverSocketChannel.accept();
            if (socketChannel != null) {
                System.out.format("服务器接收到请求：%s\n", socketChannel);
                handle(socketChannel);
            }
        }
    }

    private void handle(SocketChannel socketChannel) throws IOException {
        ByteBuffer readBuffer = ByteBuffer.allocate(1024);
        socketChannel.read(readBuffer);
        readBuffer.flip();
        byte[] bytes = new byte[readBuffer.remaining()];
        readBuffer.get(bytes);
        System.out.println("接收到请求:" + new String(bytes));

        ByteBuffer byteBuffer = ByteBuffer.wrap("服务器返回:你好".getBytes());
        socketChannel.write(byteBuffer);
    }

    public static void main(String[] args) throws IOException {
        new NioBlockServer().start();
        System.in.read();
    }
}